/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.timesoft.zk.common.generator;

import com.timesoft.common.bean.ResponseCommon;
import com.timesoft.hibernate.bean.Customer;
import com.timesoft.hibernate.bean.InformationSchemaColumns;
import java.math.BigDecimal;
import org.apache.log4j.Logger;

/**
 *
 * @author sorasaks
 */
public class CodeStringGenerator extends Generator {

    private static final Logger LOG = Logger.getLogger(CodeStringGenerator.class);

    public CodeStringGenerator(String typeCode) {
        super(typeCode);
    }

    @Override
    protected String generateCustomerCode() throws Exception {
        ResponseCommon common = (ResponseCommon) base64.stringToGenericObj(baseService.informationSchemaColumnsCoreGetCharecterMaximumLengthByTableNameAndColumnName(
                base64.genericObjToString("CUSTOMER"),
                base64.genericObjToString(CUSTOMER_CODE)));
        InformationSchemaColumns data = (InformationSchemaColumns) base64.stringToGenericObj(common.getValue());

        if (data == null) {
            return null;
        }

        Integer length = data.getCharecterMaximumLength();
        LOG.debug(":::::::::::::::::::::::: Length of CUSTOMER CODE = " + length);

        Integer count = length - 5; // Cut length of CUST-

        common = (ResponseCommon) base64.stringToGenericObj(baseService.customerCoreGetLastCustomerByCustomerCode());
        Customer customer = (Customer) base64.stringToGenericObj(common.getValue());

        if (customer == null) {
            String number = "";
            for (int i = 0; i < count; i++) {
                if (i == count - 1) {
                    number += "1";
                } else {
                    number += "0";
                }
            }
            LOG.debug(":::::::::::::::::::::::: CUSTOMER CODE = CUST-" + number);
            return "CUST-" + number;
        }

        BigDecimal codeNumber = new BigDecimal(Integer.parseInt(customer.getCustomerCode().substring(5)));
        LOG.debug(":::::::::::::::::::::::: codeNumber = " + codeNumber);
        String number = "CUST-";
        for (int i = 0; i < count - codeNumber.add(BigDecimal.ONE).toString().length(); i++) {
            number += "0";
        }
        number += codeNumber.add(BigDecimal.ONE).toString();
        LOG.debug(":::::::::::::::::::::::: CUSTOMER CODE = " + number);
        return number;
    }

    @Override
    public String generateCode() throws Exception {
        if (typeCode.equals(CUSTOMER_CODE)) {
            return generateCustomerCode();
        }
        return null;
    }
}
